package dao;


import entity.User;
import util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    public User login(User loginUser) {
        User user = null;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConn();
            ps = conn.prepareStatement("select*from user where username=? and password=?");
            ps.setString(1, loginUser.getUsername());
            ps.setString(2, loginUser.getPassword());
            rs = ps.executeQuery();
            while(rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setAge(rs.getInt("age"));
                user.setGender(rs.getString("gender"));
                user.setEmail(rs.getString("email"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {
            DBUtil.getClose(conn, ps, rs);
        }
        return user;
    }
    public void insertUser(User user){
        Connection connection = null;
        PreparedStatement statement = null;
        connection = DBUtil.getConn();
        String sql = "insert into user(username,password,age,gender,email) values (?,?,?,?,?)";
        try {
            statement = connection.prepareStatement(sql);
            statement.setString(1,user.getUsername());
            statement.setString(2,user.getPassword());
            statement.setInt(3,user.getAge());
            statement.setString(4,user.getGender());
            statement.setString(5,user.getEmail());
           int ret = statement.executeUpdate();
           if(ret == 1){
               System.out.println("注册成功！");
           }else{
               System.out.println("注册失败！");
           }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DBUtil.getClose(connection,statement,null);
        }

    }
    public static void main1(String[] args) {
        User user = new User();
        user.setUsername("bit");
        user.setPassword("123");
        UserDao userDao = new UserDao();
        User user1 = userDao.login(user);
        System.out.println(user1);
    }

    public static void main(String[] args) {
        User user = new User();
        user.setUsername("hhh");
        user.setPassword("111");
        user.setAge(12);
        user.setGender("保密");
        user.setEmail("213415@qq");
        UserDao userDao = new UserDao();
        userDao.insertUser(user);
    }
}
